package com.jingdun.sport.api.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingdun.sport.authority.SecurityChecker;
import com.jingdun.sport.bean.model.*;
import com.jingdun.sport.common.bean.ALiDaYu;
import com.jingdun.sport.common.constants.RedisConstants;
import com.jingdun.sport.common.util.PageParam;
import com.jingdun.sport.common.util.RedisUtil;
import com.jingdun.sport.security.util.SecurityUtils;
import com.jingdun.sport.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/sport/user/")
@Api(tags = "用户接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private RoomUserRelationService roomUserRelationService;

    @Autowired
    RoomUserSportRecordPerDayService roomUserSportRecordPerDayService;

    @Autowired
    private NewSOrderService newSOrderService;

    @Autowired
    SecurityChecker securityChecker;

    /**
     * 获取用户详情接口
     */
    @GetMapping("/getUserDetail")
    @ApiOperation(value = "获取用户详情接口", notes = "获取用户详情接口")
    public ApiResult getUserDetail() {
        Map m = new HashMap<String, Object>();
        m.put("userId", securityChecker.getUser().getUserId());
        com.jingdun.sport.bean.model.User userDB = userService.getUserDetail(m);
        ApiResult apiResult = new ApiResult();
        apiResult.setData(userDB);
        return apiResult;
    }

    /**
     * 修改用户接口
     */
    @PostMapping("/updateUser")
    @ApiOperation(value = "修改用户接口", notes = "修改用户接口")
    public ResponseEntity updateUser(@RequestBody com.jingdun.sport.bean.model.User user) {
        try {
            userService.updateUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApiResult apiResult = new ApiResult();
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 查看其他用户接口
     */
    @GetMapping("/getUserInfo")
    @ApiOperation(value = "查看其他用户接口", notes = "查看其他用户接口")
    public ResponseEntity getUserInfo(@RequestParam String userId) {
        User user = userService.getById(userId);
        GetUserInfoResponse getUserInfoResponse = new GetUserInfoResponse();
        BeanUtils.copyProperties(user, getUserInfoResponse);
        ApiResult apiResult = new ApiResult();
        apiResult.setData(getUserInfoResponse);
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 查看用户连续运动的日期
     */
    @GetMapping("/getUserContinuous")
    @ApiOperation(value = "查看用户房间内连续运动天数", notes = "查看用户房间内连续运动天数")
    public ResponseEntity getUserContinuous(@RequestParam String roomId, @RequestParam String userId) {
        if (roomUserRelationService.getByRoomIdAndUserId(roomId, userId)) {
            List<RoomUserSportRecordPerDay> roomUserSportRecordPerDayList = roomUserSportRecordPerDayService.getAllRecordByRoomIdAndUserId(roomId, userId);
            Room room = roomService.getById(roomId);
            List<GetUserContinuousResponse> getUserContinuousResponseList = new ArrayList<>();
            Date beginDate = com.jingdun.sport.common.util.DateUtil.getDate(room.getBeginDate());
            Date endDate = com.jingdun.sport.common.util.DateUtil.getDate(room.getEndDate());
            for (; beginDate.compareTo(endDate) <= 0; ) {
                boolean sign = false;
                for (RoomUserSportRecordPerDay roomUserSportRecordPerDay : roomUserSportRecordPerDayList) {
                    Date currentDate = Date.from(roomUserSportRecordPerDay.getGmtCreate().atZone(ZoneId.systemDefault()).toInstant());
                    if (DateUtil.isSameDay(currentDate, beginDate)) {
                        sign = true;
                    }
                }
                if (sign) {
                    GetUserContinuousResponse getUserContinuousResponse = new GetUserContinuousResponse();
                    getUserContinuousResponse.setDate(DateUtil.format(beginDate, DatePattern.NORM_DATE_FORMAT));
                    getUserContinuousResponse.setSign(1);
                    getUserContinuousResponseList.add(getUserContinuousResponse);
                } else {
                    GetUserContinuousResponse getUserContinuousResponse = new GetUserContinuousResponse();
                    getUserContinuousResponse.setDate(DateUtil.format(beginDate, DatePattern.NORM_DATE_FORMAT));
                    getUserContinuousResponse.setSign(0);
                    getUserContinuousResponseList.add(getUserContinuousResponse);
                }
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(beginDate);
                calendar.add(Calendar.DATE, 1);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
                beginDate = calendar.getTime();
            }
            return ResponseEntity.ok(getUserContinuousResponseList);
        } else {
            return ResponseEntity.status(202).body("该用户不在该房间内");
        }
    }


    /**
     * 查看用户连续运动的日期
     */
    @GetMapping("/getRoomUserContinuous")
    @ApiOperation(value = "查看房间内所有人连续运动天数", notes = "查看房间内所有人连续运动天数")
    public ResponseEntity getRoomUserContinuous(@RequestParam String roomId) {
        if (roomUserRelationService.getByRoomIdAndUserId(roomId, null)) {
            QueryWrapper<RoomUserRelation> roomUserRelationQueryWrapper = new QueryWrapper<>();
            roomUserRelationQueryWrapper.eq("room_id", roomId);
            List<RoomUserRelation> roomUserRelationList = roomUserRelationService.list(roomUserRelationQueryWrapper);
            Set<String> joinRoomUserIdSet = roomUserRelationList.stream().map(RoomUserRelation::getUserId).collect(Collectors.toSet());
            List<RoomUserSportRecordPerDay> roomUserSportRecordPerDayList = roomUserSportRecordPerDayService.getAllRecordByRoomIdAndUserId(roomId, null);
            Room room = roomService.getById(roomId);
            List<GetUserContinuousResponse> getUserContinuousResponseList = new ArrayList<>();
            List<GetRoomUserContinuousResp> getRoomUserContinuousRespList = new ArrayList<>();
            for (String joinRoomUserId : joinRoomUserIdSet) {
                User userServiceById = userService.getById(joinRoomUserId);
                int count = 0;
                Date beginDate = com.jingdun.sport.common.util.DateUtil.getDate(room.getBeginDate());
                Date endDate = com.jingdun.sport.common.util.DateUtil.getDate(room.getEndDate());
                for (; beginDate.compareTo(endDate) <= 0; ) {
//                判断用户当天是否运动过
                    for (RoomUserSportRecordPerDay roomUserSportRecordPerDay : roomUserSportRecordPerDayList) {
                        if (roomUserSportRecordPerDay.getUserId().equals(userServiceById.getUserId())) {
                            Date currentDate = Date.from(roomUserSportRecordPerDay.getGmtCreate().atZone(ZoneId.systemDefault()).toInstant());
                            if (DateUtil.isSameDay(currentDate, beginDate)) {
                                count += 1;
                                break;
                            }
                        }
                    }
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(beginDate);
                    calendar.add(Calendar.DATE, 1);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
                    beginDate = calendar.getTime();
                }
                GetRoomUserContinuousResp getRoomUserContinuousResp = new GetRoomUserContinuousResp();
                getRoomUserContinuousResp.setCount(count);
                getRoomUserContinuousResp.setNickName(userServiceById.getNickName());
                getRoomUserContinuousResp.setPic(userServiceById.getPic());
                getRoomUserContinuousResp.setUserId(userServiceById.getUserId());
                getRoomUserContinuousRespList.add(getRoomUserContinuousResp);
            }
            List<GetRoomUserContinuousResp> collect = getRoomUserContinuousRespList.stream().sorted(Comparator.comparing(GetRoomUserContinuousResp::getCount).reversed()).collect(Collectors.toList());
            return ResponseEntity.ok(collect);
        } else {
            return ResponseEntity.status(202).body("该用户不在该房间内");
        }
    }

    /**
     * 每笔收支明细表
     */
    @GetMapping("/getPerPayDetail")
    @ApiOperation(value = "每笔收支明细表", notes = "每笔收支明细表")
    @Transactional
    public ResponseEntity getPerPayDetail(Integer size, Integer current) {
        AllPayOrPerPayResp allPayOrPerPayResp = new AllPayOrPerPayResp();
        IPage<GetPerPayDetailResp> perPayDetailRespPageParam = new Page<>();
        perPayDetailRespPageParam.setSize(size);
        perPayDetailRespPageParam.setCurrent(current);
        List<GetPerPayDetailResp> perPayDetailRespList = new ArrayList<>();
        try {
            perPayDetailRespList = newSOrderService.getPerPayDetail(perPayDetailRespPageParam);
            Map allResult = newSOrderService.getAllPay();
            allPayOrPerPayResp.setAboutMoney(allResult.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        perPayDetailRespPageParam.setRecords(perPayDetailRespList);
        allPayOrPerPayResp.setGetPerPayDetailRespIPage(perPayDetailRespPageParam);
        ApiResult instance = ApiResult.getInstance();
        instance.setData(allPayOrPerPayResp);
        return ResponseEntity.ok(instance);
    }


    /**
     * 用户未提现金额表
     */
    @GetMapping("/unWithdrawal")
    @ApiOperation(value = "用户未提现金额表", notes = "用户未提现金额表")
    @Transactional
    public ResponseEntity unWithdrawal(Integer size, Integer current) {
        IPage<User> userIPage = new Page<>();
        userIPage.setSize(size);
        userIPage.setCurrent(current);
        IPage<User> page = userService.page(userIPage);
        ApiResult instance = ApiResult.getInstance();
        instance.setData(page);
        return ResponseEntity.ok(instance);
    }

    /**
     * 所有用户未提现总金额
     */
    @GetMapping("/allUserUnWithdrawalSum")
    @ApiOperation(value = "所有用户未提现总金额", notes = "所有用户未提现总金额")
    public ResponseEntity allUserUnWithdrawalSum() {
        Map sum = new HashMap();
        try {
            sum = roomService.getUserUnWithdrawalSum();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApiResult instance = ApiResult.getInstance();
        instance.setData(sum);
        return ResponseEntity.ok(instance);
    }

    /**
     * 奖金池金额表
     */
    @GetMapping("/bonusPoolsList")
    @ApiOperation(value = "奖金池金额表", notes = "奖金池金额表")
    @Transactional
    public ResponseEntity bonusPoolsList(Integer size, Integer current) {
        IPage<Room> roomIPage = new Page<>();
        roomIPage.setSize(size);
        roomIPage.setCurrent(current);
        LambdaQueryWrapper<Room> roomLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomLambdaQueryWrapper.ne(Room::getFinishedFlag, 2).eq(Room::getPrizeType, 1);
        IPage<Room> page = roomService.page(roomIPage, roomLambdaQueryWrapper);
        ApiResult instance = ApiResult.getInstance();
        instance.setData(page);
        return ResponseEntity.ok(instance);
    }

    /**
     * 奖金池总金额
     */
    @GetMapping("/bonusPools")
    @ApiOperation(value = "奖金池总金额", notes = "奖金池总金额")
    @Transactional
    public ResponseEntity bonusPools() {
        Map sum = roomService.bonusPools();
        ApiResult instance = ApiResult.getInstance();
        instance.setData(sum);
        return ResponseEntity.ok(instance);
    }
}